//
//  RequestHttpNetWrok.m
//  CFFinanceProject
//
//  Created by chunfeng on 2018/4/9.
//  Copyright © 2018年 xiaowen. All rights reserved.
//


#import "RequestHttpNetWrok.h"
@implementation RequestHttpNetWrok

//解决请求一大串字符串URL报错的方法
//NSString *str1 = [MovieRecommendAddress stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];


static RequestHttpNetWrok * operationManager;

+(RequestHttpNetWrok *)shareInstance{
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        /**
         服务器地址
         */
        operationManager = [[RequestHttpNetWrok alloc] initWithBaseURL:[NSURL URLWithString:DEF_INTERFACE_WEBVIEWSERVICE]];
        operationManager.requestSerializer.timeoutInterval = 15;
        operationManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        operationManager.responseSerializer = [AFHTTPResponseSerializer serializer];
       // [operationManager.requestSerializer setValue:TOKEN forHTTPHeaderField:@"token"];
        operationManager.responseSerializer.acceptableContentTypes =  [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"application/x-json",@"text/html", @"text/plain",@"image/jpeg", nil];
    });
    
    return operationManager;
}


/**
 *  post请求  raw json
 */
+ (RequestHttpNetWrok *)requestPostWithParameters:(NSDictionary *)parameters
                                        urlString:(NSString *)urlString
                                     finishHandle:(successBlock)finishHandle
                                       failHandle:(failtureBlock)failHandle
{
    RequestHttpNetWrok *manager = [RequestHttpNetWrok shareInstance];
    
    //        NSLog(@"parameters %@manager.baseURL  %@%@", parameters,manager.baseURL,urlString);
    
    
    operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
    [operationManager.requestSerializer setValue:TOKEN forHTTPHeaderField:@"token"];
    
    [manager POST:urlString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        // 这里可以获取到目前数据请求的进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [RequestHttpNetWrok requestSuccess:responseObject finishHandle:finishHandle failHandle:(failtureBlock)failHandle];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [RequestHttpNetWrok requestError:error failHandle:failHandle];
    }];
    
    return manager;
}

/**
 *  post请求  form-data
 */
+ (RequestHttpNetWrok *)requestPostWithFormParameters:(NSDictionary *)parameters
                                            urlString:(NSString *)urlString
                                         finishHandle:(successBlock)finishHandle
                                           failHandle:(failtureBlock)failHandle
{
    RequestHttpNetWrok *manager = [RequestHttpNetWrok shareInstance];
    
    //        NSLog(@"parameters %@manager.baseURL  %@%@", parameters,manager.baseURL,urlString);
    
    operationManager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    [operationManager.requestSerializer setValue:TOKEN forHTTPHeaderField:@"token"];

    
    // 测试代码
//    [operationManager.requestSerializer setValue:@"538e0c16-756f-4211-ac8a-42110d5900b6" forHTTPHeaderField:@"token"];

  
    
    [manager POST:urlString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        // 这里可以获取到目前数据请求的进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [RequestHttpNetWrok requestSuccess:responseObject finishHandle:finishHandle failHandle:(failtureBlock)failHandle];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [RequestHttpNetWrok requestError:error failHandle:failHandle];
    }];
    
    return manager;
}

/**
 *  get请求
 */
+ (RequestHttpNetWrok *)requestGettWithParameters:(NSDictionary *)parameters
                                        urlString:(NSString *)urlString
                                     finishHandle:(successBlock)finishHandle
                                       failHandle:(failtureBlock)failHandle
{
    RequestHttpNetWrok *manager = [RequestHttpNetWrok shareInstance];
    // 测试代码
//    [manager.requestSerializer setValue:@"538e0c16-756f-4211-ac8a-42110d5900b6" forHTTPHeaderField:@"token"];

    //    NSLog(@"parameters %@manager.baseURL  %@%@", parameters,manager.baseURL,urlString);
    
    [manager GET:urlString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        // 这里可以获取到目前数据请求的进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [RequestHttpNetWrok requestSuccess:responseObject finishHandle:finishHandle failHandle:(failtureBlock)failHandle];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [RequestHttpNetWrok requestError:error failHandle:failHandle];
    }];
    
    return manager;
}




/**
 上传图片
 */
+ (RequestHttpNetWrok *)upDataImageWithParameters:(NSDictionary *)parameters
                                        urlString:(NSString *)urlString
                                      fileNameArr:(NSArray *)fileNameArr
                                      dataPathArr:(NSArray *)dataPathArr
                                     finishHandle:(successBlock)finishHandle
                                       failHandle:(failtureBlock)failHandle{
    RequestHttpNetWrok *manager = [RequestHttpNetWrok shareInstance];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    [manager.requestSerializer setValue:TOKEN forHTTPHeaderField:@"token"];
    
    [manager.requestSerializer setValue:@"multipart/form-data; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
    [manager POST:urlString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
  
            for (int i = 0; i < fileNameArr.count; i ++) {
                
                [formData appendPartWithFileData:dataPathArr[i] name:@"image" fileName:fileNameArr[i] mimeType:@"image/jpeg"];
            }
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [RequestHttpNetWrok requestSuccess:responseObject finishHandle:finishHandle failHandle:(failtureBlock)failHandle];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [RequestHttpNetWrok requestError:error failHandle:failHandle];
    }];
    
    return manager;
}



/**
 *  网络请求成功处理
 */
+ (void)requestSuccess:(id)responseObject finishHandle:(successBlock)finishHandle failHandle:(failtureBlock)failHandle{
    
    id json = [NSJSONSerialization
               JSONObjectWithData:responseObject
               options:kNilOptions
               error:nil];
    if([json[@"code"] integerValue] != 2000&&[json[@"code"] integerValue] != 1010){
        NSString * message = json[@"msg"];
        [AlertUtil alertMessage:message];
    }
    
    //    NSLog(@"--------------json %@",json);
    
    //    if ([json[@"code"] integerValue] == 200) {
    //正确逻辑处理
    finishHandle(json);
    //    }else{
    //        //错误逻辑处理
    //        [CFUtility showTips:json[@"data"][@"message"]];
    //
    //        NSError *error = [NSError errorWithDomain:ERRORDAOMAIN code:[json[@"code"] integerValue] userInfo:responseObject];
    //        failHandle(error);
    //    }
}


/**
 *  网络请求失败处理
 */
+ (void)requestError:(NSError *)error failHandle:(failtureBlock)failHandle{

    if (error.code == 401) {
        
        //        CFNoteLoginVC * loginVC = (CFNoteLoginVC *)[CFUtility getVC:@"CFNoteLoginVC" Storyboard:LOGIN];
        //        UIViewController *rootViewController = [[[UIApplication sharedApplication] keyWindow] rootViewController];
        //        CFNavViewController *nav = [[CFNavViewController alloc] initWithRootViewController:loginVC];
        //        [rootViewController presentViewController:nav animated:NO completion:nil];
        
    }
    
    NSString *message;
    
    
    
    if(error.code == kCFURLErrorNotConnectedToInternet || error.code == kCFURLErrorCannotConnectToHost)
    {
        message = @"网络不可用，请检查网络连接";
    }else if (error.code == kCFURLErrorTimedOut)
    {
        message = @"网络请求超时";
    }else
    {
        message = @"请求失败，请稍后再试";
    }
    [CFUtility showTips:message];
    
    CC_LOG_VALUE(error.localizedDescription);
    
    failHandle(error);
}

@end
